import React from "react";

const { Suspense, unstable_SuspenseList: SuspenseList } = React as any;

const resource = {
    user: (() => {
        let status = false;
        let p = new Promise<any>((re, rj) => {
            setTimeout(() => {
                re(undefined)
            }, 3000);
        }).then(e => {
            status = true;
        })

        return {
            read: () => {
                if (status === true) {
                    return { name: 123 };
                } else {
                    throw p;
                }
            }
        }
    })(),
    posts: (() => {
        let status = false;
        let p = new Promise<any>((re, rj) => {
            setTimeout(() => {
                re(undefined)
            }, 1000);
        }).then(e => {
            status = true;
        })

        return {
            read: () => {
                if (status === true) {
                    return [
                        {
                            id: 1,
                            text: "22"
                        },
                        {
                            id: 2,
                            text: "33"
                        }
                    ];
                } else {
                    throw p;
                }
            }
        }
    })()
}

export default function ProfilePage() {
    return (
        <SuspenseList revealOrder="forwards">
            <Suspense
                fallback={<h1>Loading profile...</h1>}
            >
                <ProfileDetails />
            </Suspense>
            <Suspense
                fallback={<h1>Loading posts...</h1>}
            >
                <ProfileTimeline />
            </Suspense>
        </SuspenseList>
    );
}

function ProfileDetails() {
    // Try to read user info, although it might not have loaded yet
    const user = resource.user.read();
    return <h1>{user.name}</h1>;
}

function ProfileTimeline() {
    // Try to read posts, although they might not have loaded yet
    const posts = resource.posts.read();
    return (
        <ul>
            {posts.map(post => (
                <li key={post.id}>{post.text}</li>
            ))}
        </ul>
    );
}